package com.crimerank;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crimerank.data.BusRoute;
import com.crimerank.data.StopCrime;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class StopRoutes extends BaseListActivity {

	StopCrime obj = null;
	BusRouteAdapter m_adapter;
	Bundle loc;
	HashMap<String, BusRoute> routesMap;
	ArrayList<String> routes;
	Bundle stopLoc = new Bundle();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stoproutes);

		this.loc = getIntent().getExtras().getBundle("loc");

		obj = (StopCrime) getIntent().getSerializableExtra("StopCrimeObj");

		// Display the bus stop name.
		TextView stopName = (TextView) findViewById(R.id.stopPredictionName);
		stopName.setText(obj.getName());

		// Display stop CrimeRank.
		TextView stopRank = (TextView) findViewById(R.id.stopScheduleRank);
		stopRank.setText("Rank: " + obj.getRank());

		// Setup the list adapter.
		m_adapter = new BusRouteAdapter(this, R.layout.routesrow,
				new ArrayList<BusRoute>());
		setListAdapter(m_adapter);

		// Retrieve data and populate the ListView.
		try {
			requestData(obj.getStop_id());
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void requestData(String stop_id) throws JSONException {
		try {
			String url = getResources().getString(
					R.string.URL_BUS_STOP_SCHEDULE);
			String query = String.format("stopId=%s&api_key=%s",
					URLEncoder.encode(stop_id, "UTF-8"),
					URLEncoder.encode("s2f5rag8pa5fz53mg2e7s4et", "UTF-8"));

			// Perform the HTTP request
			String result = doHttpRequest(url, query);

			// Process results and display list
			processJson(result);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void processJson(String result) throws JSONException {

		JSONObject jo = new JSONObject(result);
		JSONArray ja = jo.getJSONArray("ScheduleArrivals");

		// The JSON tree potentially contains schedule information for several
		// routes. Each departure time is stored under the correct route.
		this.routesMap = new HashMap<String, BusRoute>();

		// Iterate through the listings of departure times.
		for (int i = 0; i < ja.length(); ++i) {
			JSONObject tmp = (JSONObject) ja.get(i);

			String directionNum = tmp.getString("DirectionNum");
			String routeId = tmp.getString("RouteID");
			String time = tmp.getString("ScheduleTime");
			String directionText = tmp.getString("TripDirectionText");
			String tripHeadsign = tmp.getString("TripHeadsign");

			// If the schedule for the specified route+direction has already
			// been started, just add to it, otherwise, create a new BusRoute
			// object and begin the schedule.
			String key = routeId + "_" + directionNum;

			if (routesMap.containsKey(key)) {
				routesMap.get(key).setSchedule(time);
			} else {
				BusRoute tempRoute = new BusRoute(routeId, directionNum,
						directionText, tripHeadsign);
				tempRoute.setSchedule(time);
				routesMap.put(key, tempRoute);

				// Also, populate the current ListView with the route.
				m_adapter.add(tempRoute);
			}
		}

		// Also, retrieve the stop lat/lon.
		// It's also available from the static data on our server, but why not
		// grab it here too ;-).
		jo = jo.getJSONObject("Stop");
		Double lat = new Double(jo.getString("Lat"));
		Double lon = new Double(jo.getString("Lon"));
		stopLoc.putDouble("lat", lat);
		stopLoc.putDouble("lon", lon);
		// jo.getString("Routes");

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent myIntent = new Intent(v.getContext(), RouteSchedule.class);
		myIntent.putExtra("loc", loc);
		myIntent.putExtra("BusRoute", m_adapter.getItem(position));
		myIntent.putExtra("StopName", obj.getName());
		myIntent.putExtra("stopId", obj.getStop_id());
		myIntent.putExtra("stopLoc", stopLoc);
		startActivityForResult(myIntent, 0);
	}

	private class BusRouteAdapter extends ArrayAdapter<BusRoute> {

		private ArrayList<BusRoute> items;

		public BusRouteAdapter(Context context, int textViewResourceId,
				ArrayList<BusRoute> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.routesrow, null);
			}

			BusRoute r = items.get(position);

			if (r != null) {
				TextView textName = (TextView) view
						.findViewById(R.id.routeName);
				textName.setText(r.getRouteId() + ": " + r.getDirectionText()
						+ " to " + r.getTripHeadsign());
			}

			return view;
		}
	}

	public void onClick(View v) {
		Intent myIntent;
		switch (v.getId()) {
		case (R.id.imageMap):
			myIntent = new Intent(v.getContext(), Map.class);
			myIntent.putExtra("points", getIntent()
					.getParcelableArrayListExtra("points"));
			myIntent.putExtra("mapType", "geoPoint");
			myIntent.putExtra("loc", loc);
			startActivity(myIntent);
			break;
		case (R.id.imageCrime):
			myIntent = new Intent(v.getContext(), StationCrime.class);
			myIntent.putExtra("StopCrimeObj", obj);
			startActivity(myIntent);
			break;
		case (R.id.imageHome):
			myIntent = new Intent(v.getContext(), Home.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(myIntent);
			break;
		}
	}

}
